<?php

/**
	Peak Template Helper

	The contents of this file are subject to the terms of the GNU General
	Public License Version 2.0. You may not use this file except in
	compliance with the license. Any of the license terms and conditions
	can be waived if you get permission from the copyright holder.

	Copyright (c) 2011 Bandit Media
	Jermaine Marée

		@package bandit
		@version 1.1
**/

//! Bandit Helper
class bandit extends FeatherTheme {

	/**
		Print language option
			@return string
			@param $key string
			@public
	**/
	static function lang($key,$default='') {
		echo self::get_lang($key,$default);
	}

	/**
		Compiles an array of HTML attributes into an attribute string
			@return string
			@param $attrs array
			@public
	**/
	static function attributes($attrs) {
		if(!empty($attrs)) {
			$attributes='';
			foreach($attrs as $key=>$val)
				$attributes.=' '.$key.'="'.$val.'"';
			return $attributes;
		}
	}

	/**
		Limit words in a string
			@return string
			@param $str string
			@param $Length int
			@public
	**/
	static function limit_words($str,$length) {
		$str=explode(' ',$str);
		return implode(' ',array_slice($str,0,$length));
	}

	/**
		Build link element
			@return string
			@param $rel string
			@param $href string
			@param $title string
			@public
	**/
	static function link($rel='',$href='',$title=NULL) {
		$attr=array (
			'rel'=>$rel,
			'href'=>$href,
		);
		if (!empty($title))
			$attr['title']=$title;
		$link='<link'.self::attributes($attr).'>';
		return $link."\n";
	}

	/**
		Title element - builds title element based on page
			@return string
			@param $separator string
			@public
	**/
	static function get_title($separator='-') {
		$separator=apply_filters('bandit_title_separator', $separator);
		if (is_front_page())
			$title=get_bloginfo('name').' '.$separator.' '.get_bloginfo('description');
		else
			$title=wp_title($separator,false,'right').get_bloginfo('name');
		return apply_filters('bandit_title', $title);
	}
	static function title($separator='-') {
		echo self::get_title($separator);
	}

	/**
		Theme stylesheets
			@public
	**/
	static function stylesheets() {
		$stylesheet=self::link('stylesheet',get_bloginfo('stylesheet_url'));
		if(self::get_option('theme_style'))
			$stylesheet.=self::link('stylesheet',get_template_directory_uri().'/styles/'.self::get_option('theme_style'));
		if(self::get_option('custom_styles'))
			$stylesheet.=self::link('stylesheet',get_template_directory_uri().'/style-custom.css');
		echo $stylesheet;
	}

	/**
		Site Name
			@return string
			@param $id string
			@param $class string
			@param $tag1 string
			@param $tag2 string
			@public
	**/
	static function get_site_name($id='logo',$class=NULL,$tag1='h1',$tag2='p') {
		// Check for custom logo
		$img_logo=self::get_option('custom_logo');
		// Set attributes
		if(!empty($id))
			$attrs['id']=$id;
		if(!empty($class))
			$attrs['class']=$class.($img_logo?' logo-img':'');
		elseif($img_logo)
			$attrs['class']='logo-img';
		$attrs=isset($attrs)?self::attributes($attrs):'';
		// Set tags
		$tag=(is_front_page() || is_home())?$tag1:$tag2;
		// Set URL
		$url=home_url('/');
		// Text/Image Logo
		$name=$img_logo?'<img src="'.$img_logo.'" alt="'.get_bloginfo('name').
			'">':get_bloginfo('name');
		// Set site name
		$sitename='<'.$tag.$attrs.'><a href="'.$url.'" rel="home">'.
			$name.'</a></'.$tag.'>'."\n";
		return apply_filters('bandit_site_name', $sitename);
	}
	static function site_name($id='logo',$class=NULL,$tag1='h1',$tag2='p') {
		echo self::get_site_name($id,$class,$tag1,$tag2);
	}

	/**
		Site description
			@return string
			@param $id string
			@public
	**/
	static function get_site_desc($id='tagline',$class=NULL) {
		if(self::get_option('disable_tagline'))
			return FALSE;
		// Set attributes
		if(!empty($id))
			$attrs['id']=$id;
		if(!empty($class))
			$attrs['class']=$class;
		$attrs=isset($attrs)?self::attributes($attrs):'';
		// Set site description
		$sitedesc='<p'.$attrs.'>'.get_bloginfo('description').'</p>';
		return apply_filters('bandit_site_desc', $sitedesc);
	}
	static function site_desc($id='tagline',$class=NULL) {
		echo self::get_site_desc($id,$class);
	}

	/**
		Time ago
			@return string
			@params $max int
			@public
	**/
	static function time_ago($max=31) {
		// Post date
		$post_date=get_the_time('U');
		// Current time
		$now=current_time('timestamp');
		// Difference
		$date_diff=$now-$post_date;
		// How many days ago?
		$days_ago=(floor($date_diff/(60*60*24)));
		// Set date
		if($days_ago <= 31) {
			$date=human_time_diff($post_date,$now);
			$date.=' '.self::get_lang('post_meta_ago',__('ago','creatic'));
		} else {
			$date=the_time('F j, Y');
		}
		// Print date
		echo $date;
	}

	/**
		Get images attached to post
			@param $orderby string
			@param $order string
			@public
	**/
	static function get_post_images($orderby='menu_order',$order='ASC') {
		global $post;
		$images=get_posts('post_type=attachment&post_mime_type=image&numberposts=-1&post_parent='.
			$post->ID.'&orderby='.$orderby.'&order='.$order);
		return $images;
	}

	/**
		Get post liked count
			@public
	**/
	static function get_post_liked_count() {
		global $post;
		$liked=get_post_meta($post->ID,'_bandit_liked',TRUE);
		return $liked?$liked:'0';
	}
	static function post_liked_count() {
		echo self::get_post_liked_count();
	}

	/**
		Liked class
			@public
	**/
	static function liked_class() {
		global $post;
		$liked=array();
		if(isset($_COOKIE['_bandit_liked'])) {
			$cookie=base64_decode($_COOKIE['_bandit_liked']);
			$liked=explode('|',$cookie);
		}
		if(in_array($post->ID,$liked))
			echo 'class="active"';
	}

	/**
		Archive heading
			@return string
			@public
	**/
	static function get_archive_heading() {
		// Author archive page
		if(is_author()) {
			if(get_query_var('author_name'))
				$author=get_userdatabylogin(get_query_var('author_name'));
			else
				$author=get_userdata(get_query_var('author'));
			$heading=self::get_lang('archive_heading_author',__('Author:','creatic')).' '.$author->display_name;
		}
		// Category archive page
		if(is_category()) {
			$heading=self::get_lang('archive_heading_category',__('Category:','creatic')).' '.single_cat_title('', false);
		}
		// Daily archive
		if(is_day()) {
			$heading=self::get_lang('archive_heading_day',__('Daily:','creatic')).get_the_time(' F j, Y');
		}
		// Monthly archive
		if(is_month()) {
			$heading=self::get_lang('archive_heading_month',__('Monthly:','creatic')).get_the_time(' F Y');
		}
		// Tag archive page
		if(is_tag()) {
			$heading=self::get_lang('archive_heading_tag',__('Tagged:','creatic')).' '.single_tag_title('', false);
		}
		// Yearly archive page
		if(is_year()) {
			$heading=self::get_lang('archive_heading_year',__('Yearly:','creatic')).get_the_time(' Y');
		}
		return $heading;
	}
	static function archive_heading() { echo self::get_archive_heading(); }

	/**
		Show post navigation?
			@return boolean
			@public
	**/
	static function show_post_nav() {
		global $wp_query;
		return ($wp_query->max_num_pages > 1);
	}

	/**
		Comments enabled?
			@return boolean
			@public
	**/
	static function comments_enabled() {
		if(is_page())
			$option=self::get_option('comments_pages');
		if(is_single())
			$option=self::get_option('comments_posts');
		$option=('1'===$option)?FALSE:TRUE;
		return $option;
	}

	/**
		Social Media Links
			@public
	**/
	static function social_media_links($attrs = NULL) {
		// Set attributes
		$attrs = isset($attrs)?self::attributes($attrs):'';
		// Get links
		$links = BanditSocial::get_items();
		if($links) {
			$output = '<ul'.$attrs.'>';
			// Loop through links
			foreach($links as $link) {
				$output .= '<li><a href="'.$link['url'].'"><span class="icon"><img src="'.
					$link['icon'].'"></span><span class="icon-title">'.$link['name'].'</span></li>';
			}
			$output .= '</ul>';
			// Print links
			echo $output;
		}
	}

	/**
		Resize images dynamically using wp built in functions
		Victor Teixeira

		Example use:
 
		<?php 
		$thumb = get_post_thumbnail_id(); 
		$image = vt_resize( $thumb, '', 140, 110, true );
		?>
		<img src="<?php echo $image[url]; ?>" width="<?php echo $image[width]; ?>" height="<?php echo $image[height]; ?>" />

		@param int $attach_id
		@param string $img_url
		@param int $width
		@param int $height
		@param bool $crop
		@return array
	**/
	static function vt_resize( $attach_id = null, $img_url = null, $width, $height, $crop = false ) {
		// this is an attachment, so we have the ID
		if ( $attach_id ) {
			$image_src = wp_get_attachment_image_src( $attach_id, 'full' );
			$file_path = get_attached_file( $attach_id );
		// this is not an attachment, let's use the image url
		} else if ( $img_url ) {
			$file_path = parse_url( $img_url );
			$file_path = $_SERVER['DOCUMENT_ROOT'] . $file_path['path'];
			//$file_path = ltrim( $file_path['path'], '/' );
			//$file_path = rtrim( ABSPATH, '/' ).$file_path['path'];
			$orig_size = getimagesize( $file_path );
			$image_src[0] = $img_url;
			$image_src[1] = $orig_size[0];
			$image_src[2] = $orig_size[1];
		}

		$file_info = pathinfo( $file_path );
		$extension = '.'. $file_info['extension'];

		// the image path without the extension
		$no_ext_path = $file_info['dirname'].'/'.$file_info['filename'];
		$cropped_img_path = $no_ext_path.'-'.$width.'x'.$height.$extension;

		// checking if the file size is larger than the target size
		// if it is smaller or the same size, stop right here and return
		if ( $image_src[1] > $width || $image_src[2] > $height ) {
			// the file is larger, check if the resized version already exists (for $crop = true but will also work for $crop = false if the sizes match)
			if ( file_exists( $cropped_img_path ) ) {
				$cropped_img_url = str_replace( basename( $image_src[0] ), basename( $cropped_img_path ), $image_src[0] );
				$vt_image = array (
					'url' => $cropped_img_url,
					'width' => $width,
					'height' => $height
				);
				return $vt_image;
			}
			// $crop = false
			if ( $crop == false ) {
				// calculate the size proportionaly
				$proportional_size = wp_constrain_dimensions( $image_src[1], $image_src[2], $width, $height );
				$resized_img_path = $no_ext_path.'-'.$proportional_size[0].'x'.$proportional_size[1].$extension;		
				// checking if the file already exists
				if ( file_exists( $resized_img_path ) ) {
					$resized_img_url = str_replace( basename( $image_src[0] ), basename( $resized_img_path ), $image_src[0] );
					$vt_image = array (
						'url' => $resized_img_url,
						'width' => $proportional_size[0],
						'height' => $proportional_size[1]
					);
					return $vt_image;
				}
			}
			// no cache files - let's finally resize it
			$new_img_path = image_resize( $file_path, $width, $height, $crop );
			if(!isset($new_img_path->errors)) {
				$new_img_size = getimagesize( $new_img_path );
				$new_img = str_replace( basename( $image_src[0] ), basename( $new_img_path ), $image_src[0] );
				// resized output
				$vt_image = array (
					'url' => $new_img,
					'width' => $new_img_size[0],
					'height' => $new_img_size[1]
				);
				return $vt_image;
			}
		}
		// default output - without resizing
		$vt_image = array (
			'url' => $image_src[0],
			'width' => $image_src[1],
			'height' => $image_src[2],
			'noresize' => TRUE
		);
		return $vt_image;
	}

	/**
		Dynamic Image Resizing
			@public
	**/
	static function dynamic_resize($attach_id=null,$img_url=null,$width,$height,$crop=false) {
		// Resize image
		$dynamic_image=self::vt_resize($attach_id,$img_url,$width,$height,$crop);

		// Was image resized ?
		if(!isset($dynamic_image['noresize'])) {
			// Get upload dir and URL
			$upload_dir=wp_upload_dir();
			$upload_url=$upload_dir['baseurl'];
			// Get image path
			$image=split($upload_url,$dynamic_image['url']);
			// Check if in DB
			global $wpdb;
			$result=$wpdb->get_row("SELECT * FROM bandit_images WHERE image_file = '$image[1]' ", ARRAY_A);
			// If no result, enter into DB
			if(!$result) {
				$wpdb->insert('bandit_images',array(
						'post_id'=>$attach_id,
						'image_file'=>$image[1]
					)
				);
			}
		}
		return $dynamic_image;
	}

	/**
		TimThumb Image Builder
			@public
	**/
	static function timthumb($image_id=NULL,$post_id=NULL,$width=NULL,$height=NULL) {
		if($image_id && $post_id && $width && $height) {
			// Get attachment
			$attach=wp_get_attachment_image_src($image_id,'full');
			// WPMU Support
			global $blog_id;
			if (isset($blog_id) && $blog_id > 0) {
				$imageParts = explode('/files/', $attach[0]);
				if (isset($imageParts[1])) {
					$attach[0] = '/blogs.dir/' . $blog_id . '/files/' . $imageParts[1];
				}
			}
			// Set image url, width, height
			$img=$attach[0].'&w='.$width.'&h='.$height;
			// Get TimThumb options
			$options='sharpen|quality|greyscale|brightness|contrast|crop';
			foreach(explode('|',$options) as $option)
				$$option=get_post_meta($post_id,'_bandit_portfolio_timthumb_'.$option,TRUE);
			// Sharpen
			if($sharpen)
				$img.='&s=1';
			// Quality
			if($quality)
				$img.='&q='.$quality;
			// Filters
			if($greyscale || $brightness || $contrast) {
				$prefix=FALSE;
				$img.='&f=';
				// Greyscale
				if($greyscale) {
					$img.='2';
					$prefix=TRUE;
				}
				// Brightness
				if($brightness) {
					$img.=($prefix?'|3,':'3,');
					$img.=$brightness;
					$prefix=TRUE;
				}
				// Contrast
				if($contrast) {
					$img.=($prefix?'|4,':'4,');
					$img.=$contrast;
				}
			}
			// Alignment
			if('c'!=$crop)
				$img.='&a='.$crop;
			// Build image array
			$image['url']=get_template_directory_uri().'/thumb.php?src='.$img;
			$image['width']=$width;
			$image['height']=$height;
			return $image;
		}
	}

	/**
		TimThumb Image Builder
			@public
	**/
	static function timthumb_slider($image_id=NULL,$width=NULL,$height=NULL) {
		if($image_id) {
			// Get attachment
			$attach=wp_get_attachment_image_src($image_id,'full');
			// WPMU Support
			global $blog_id;
			if (isset($blog_id) && $blog_id > 0) {
				$imageParts = explode('/files/', $attach[0]);
				if (isset($imageParts[1])) {
					$attach[0] = '/blogs.dir/' . $blog_id . '/files/' . $imageParts[1];
				}
			}
			// Set image url, width, height
			$img=$attach[0].'&w='.$width.'&h='.$height;
			// Build image array
			$image=get_template_directory_uri().'/thumb.php?src='.$img;
			return $image;
		}
	}

}